/*
 * GrantRequestStatusChangeCancelledView.java
 *
 * Created on November 20, 2008, 10:11 AM
 */

package researchgrants.parts.GrantRequest.statusChanges;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import researchgrants.parts.GrantRequest.GrantRequest;
import researchgrants.parts.LoggedData.LoggedData;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsDate;
import researchgrants.parts.db.Db;
import researchgrants.parts.panelsManager.LoggedDataPanelsManager;

/**
 * A view to edit an existing or input a new GrantRequestStatusChangeSubmitted
 * @author  DOStudent1
 */
public class GrantRequestStatusChangeSubmittedView extends GrantRequestStatusChangeView  {

    private Window parent;
    private final static int hgap=0;

    // defferentiate between new (to be saved) and existing StatusChangeSubmitted
    private boolean isNew;

    // if existing StatusChangeSubmitted, this is it
    private GrantRequestStatusChangeSubmitted grantRequestStatusChangeSubmitted;

    // if new StatusChangeSubmitted, need this supplement data (to connect to upon save)
    private GrantRequest grantRequest;

    // global-style component
    private ActionListener savedActionListener;
    private ActionListener cancelActionListener;
    private JButton btnSaveAll, btnCancel;
    private LoggedDataPanelsManager submissionDateView, expectedDecisionDateView;
    private JPanel pnlWarnings=new JPanel();
    
    /** Will creates a new (empty) Submission and connect it to the given grantRequest*/
    public GrantRequestStatusChangeSubmittedView(Window parent, GrantRequest grantRequest, ActionListener savedActionListener, ActionListener cancelActionListener) {
//        super()
        initComponents();
        this.parent=parent;
        this.grantRequest=grantRequest;
        this.savedActionListener=savedActionListener;
        this.cancelActionListener=cancelActionListener;
        isNew=true;

        initDisplay();
    }

    /** displays an existing Submission */
    public GrantRequestStatusChangeSubmittedView(Window parent, GrantRequestStatusChangeSubmitted grantRequestStatusChangeSubmitted) {
        initComponents();
        this.parent=parent;
        this.grantRequestStatusChangeSubmitted=grantRequestStatusChangeSubmitted;
        isNew=false;

        initDisplay();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlID = new javax.swing.JPanel();
        lblCaptionId = new javax.swing.JLabel();
        lblId = new javax.swing.JLabel();
        pnlSubmissionDate = new javax.swing.JPanel();
        lblCaptionSubmissionDate = new javax.swing.JLabel();
        pnlFieldSubmissionDate = new javax.swing.JPanel();
        pnlExpectedDecisionDate = new javax.swing.JPanel();
        lblCaptionExpectedDecisionDate = new javax.swing.JLabel();
        pnlFieldExpectedDecisionDate = new javax.swing.JPanel();
        pnlOptionalButtons = new javax.swing.JPanel();

        setName("Form"); // NOI18N
        setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));

        pnlID.setName("pnlID"); // NOI18N
        pnlID.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(researchgrants.ResearchGrantsApp.class).getContext().getResourceMap(GrantRequestStatusChangeSubmittedView.class);
        lblCaptionId.setText(resourceMap.getString("lblCaptionId.text")); // NOI18N
        lblCaptionId.setName("lblCaptionId"); // NOI18N
        pnlID.add(lblCaptionId);

        lblId.setText(resourceMap.getString("lblId.text")); // NOI18N
        lblId.setName("lblId"); // NOI18N
        pnlID.add(lblId);

        add(pnlID);

        pnlSubmissionDate.setName("pnlSubmissionDate"); // NOI18N
        pnlSubmissionDate.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionSubmissionDate.setText(resourceMap.getString("lblCaptionSubmissionDate.text")); // NOI18N
        lblCaptionSubmissionDate.setName("lblCaptionSubmissionDate"); // NOI18N
        pnlSubmissionDate.add(lblCaptionSubmissionDate);

        pnlFieldSubmissionDate.setName("pnlFieldSubmissionDate"); // NOI18N
        pnlFieldSubmissionDate.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlSubmissionDate.add(pnlFieldSubmissionDate);

        add(pnlSubmissionDate);

        pnlExpectedDecisionDate.setName("pnlExpectedDecisionDate"); // NOI18N
        pnlExpectedDecisionDate.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionExpectedDecisionDate.setText(resourceMap.getString("lblCaptionExpectedDecisionDate.text")); // NOI18N
        lblCaptionExpectedDecisionDate.setName("lblCaptionExpectedDecisionDate"); // NOI18N
        pnlExpectedDecisionDate.add(lblCaptionExpectedDecisionDate);

        pnlFieldExpectedDecisionDate.setName("pnlFieldExpectedDecisionDate"); // NOI18N
        pnlFieldExpectedDecisionDate.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlExpectedDecisionDate.add(pnlFieldExpectedDecisionDate);

        add(pnlExpectedDecisionDate);

        pnlOptionalButtons.setName("pnlOptionalButtons"); // NOI18N
        pnlOptionalButtons.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        add(pnlOptionalButtons);
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel lblCaptionExpectedDecisionDate;
    private javax.swing.JLabel lblCaptionId;
    private javax.swing.JLabel lblCaptionSubmissionDate;
    private javax.swing.JLabel lblId;
    private javax.swing.JPanel pnlExpectedDecisionDate;
    private javax.swing.JPanel pnlFieldExpectedDecisionDate;
    private javax.swing.JPanel pnlFieldSubmissionDate;
    private javax.swing.JPanel pnlID;
    private javax.swing.JPanel pnlOptionalButtons;
    private javax.swing.JPanel pnlSubmissionDate;
    // End of variables declaration//GEN-END:variables


    // displays the content
    private void initDisplay() {
        // must init the button so it will be enabled or disabled by the other fields
        if (isNew) {
            btnSaveAll=new JButton("Save Submission");
            btnSaveAll.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    createNewSubmissionFromFields();
                }
            });

            btnCancel=new JButton("Leave Unchanged");
            btnCancel.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    cancelActionListener.actionPerformed(e);
                }
            });
            
        }

        ///////////////////////////
        // Displays the content
        ///////////////////////////
    
        if (isNew) {
            lblId.setText("<Auto>");
        } else {
            lblId.setText(Integer.toString(grantRequestStatusChangeSubmitted.getStatusChangeId()));
        }

        LoggedData submissionDate=null, expectedDecisionDate=null;
        if (!isNew) {
            submissionDate=grantRequestStatusChangeSubmitted.getLoggedDataSubmissionDate();
            expectedDecisionDate=grantRequestStatusChangeSubmitted.getLoggedDataExpectedDecisionDate();
        }
        {
            LoggedDataPanelsDate panels=new LoggedDataPanelsDate();
            ChangeListener changeEventListener = new SubmissionDateChangeListener(panels);
            submissionDateView=createLoggedDataPanelManager(true, isNew, panels, parent, submissionDate, pnlFieldSubmissionDate, changeEventListener);
        }
        expectedDecisionDateView=createLoggedDataPanelManager(false, isNew, new LoggedDataPanelsDate(), parent, expectedDecisionDate, pnlFieldExpectedDecisionDate);
        


        
        pnlOptionalButtons.removeAll();
        if (isNew) {

            JPanel pnlOptionalButtons3=new JPanel(new GridLayout());
            pnlOptionalButtons3.add(btnSaveAll);
            pnlOptionalButtons3.add(btnCancel);

            JPanel pnlOptionalButtons2=new JPanel(new BorderLayout(0, 0));
            pnlOptionalButtons2.add(pnlWarnings, BorderLayout.NORTH);
            pnlOptionalButtons2.add(pnlOptionalButtons3, BorderLayout.CENTER);
            pnlOptionalButtons.add(pnlOptionalButtons2);

        }
        
        // revalidate the form
        validateEntireForm();
        
    }

    // Creates a new GrantRequestStatusChangeAward from the fields
    private void createNewSubmissionFromFields() {
        try {
            // creates the common GrantRequestStatusChange part
            int newStatusChangeId = GrantRequestStatusChangeSubmitted.createNewStatusChangeForGrantRequest(grantRequest, GrantRequestStatusChangeSubmitted.dbString);

            // saves the independent data
            Connection conn = Db.openDbConnection();
            PreparedStatement statement = Db.createPreparedStatement(conn, "INSERT INTO tblGrantRequestsStatusChangesSubmitted (GrantRquestStatusChangeID, SubmissionDateRef, ExpectedDecisionDateRef) VALUES (?, ?, ?)");

            statement.setInt(1, newStatusChangeId);
            
            statement.setInt(2, saveLoggedDataPanelsManagerData(submissionDateView));
            statement.setInt(3, saveLoggedDataPanelsManagerData(expectedDecisionDateView));

            statement.executeUpdate();
            statement.close();
            Db.closeDbConnection(conn);

            // loads the newly created Cancel
            this.grantRequestStatusChangeSubmitted=GrantRequestStatusChangeSubmitted.getByStatusChangeId(newStatusChangeId);
            // refreshes the GrantRequest to reload the manually added data
            grantRequest.refreshData();
            
            // notifies the listeners. the GrantRequestView needs to redisplay
            savedActionListener.actionPerformed(new ActionEvent(this, 1, "Saved new Sumbission StatusChange"));

        } catch (SQLException ex) {
            Logger.getLogger(GrantRequestStatusChangeSubmittedView.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    }

    
    /////////////////////////
    // Validates the form
    /////////////////////////
    
    // each individual component is validates/invalidates seperately, using its designated Listener
    // the entire form is revalidated after any idnividual change
    
    private boolean isSubmissionDateValid=false;
    
    
    private void validateEntireForm() {
        setSaveEnabled(isSubmissionDateValid);
        pnlWarnings.removeAll();
        int warnings=0;
        if (!isSubmissionDateValid) {
            JLabel lblWarning=new JLabel("You must select a submission date");
            lblWarning.setForeground(Color.RED);
            pnlWarnings.add(lblWarning);
            warnings++;
        }
        

        pnlWarnings.setLayout(new GridLayout(warnings, 1));
        pnlWarnings.revalidate();
    }

    private void setSaveEnabled(boolean enabled) {
        // will only be used when a global save button is availalbe
        if (btnSaveAll!=null) {
            btnSaveAll.setEnabled(enabled);
        }
    }

    
    class SubmissionDateChangeListener implements ChangeListener {
        LoggedDataPanelsDate panels;
        public SubmissionDateChangeListener(LoggedDataPanelsDate panels) {
            this.panels=panels;
        }

        public void stateChanged(ChangeEvent e) {
            isSubmissionDateValid=panels.isValid() && (!panels.isEmpty());
            validateEntireForm();
        }
    }

}
